package com.huluobo.lib_base.mvvm

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModelProvider
import com.blankj.utilcode.util.ToastUtils
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.lang.reflect.ParameterizedType

/**
 *  Created by LC on 2025/10/8.
 */
abstract class BaseActivity<VDB : ViewDataBinding, VM : BaseViewModel> : AppCompatActivity() {
    private val type by lazy { (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments }

    protected val binding: VDB by lazy {
        val clazz = type[0] as Class<VDB>
        val method = clazz.getMethod("inflate", LayoutInflater::class.java)
        method.invoke(null, layoutInflater) as VDB
    }

    protected val vm: VM by lazy {
        val clazz = type[1] as Class<VM>
        ViewModelProvider(this)[clazz]
    }

    open fun onError(t: Throwable) {
        ToastUtils.showLong(t.message)
        Log.e("TagA", "onError:${t.message}")
        t.printStackTrace()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        vm.onFailed.observe(this, ::onError)
        initView()
        initData()
        EventBus.getDefault().register(this)
    }

    abstract fun initData()

    abstract fun initView()

    @Subscribe(threadMode = ThreadMode.MAIN)
    open fun onEvent(messageEvent: MessageEvent) {

    }

    open fun <T> startAct(activity: Class<T>) {
        val intent = Intent(this, activity)
        startActivity(intent)
    }
}